package com.itmuch.box.service.tag;

import java.util.Set;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Sets;
import com.itmuch.box.core.base.BaseService;
import com.itmuch.box.dao.mid.MidContentTagRepository;
import com.itmuch.box.dao.tag.TagRepository;
import com.itmuch.box.domain.mid.entity.MidContentTag;
import com.itmuch.box.domain.tag.entity.Tag;

@Service
@Transactional
public class TagService extends BaseService<TagRepository, Tag> {
    @Autowired
    private MidContentTagRepository midContentTagRepository;

    public Tag findTopByName(String name) {
        return this.dao.findTopByName(name);
    }

    public Set<Tag> findByIdIn(Set<Integer> ids) {
        return this.dao.findByIdIn(ids);
    }

    public Set<Integer> findTagIdsByContentId(Integer contentId) {
        Set<MidContentTag> set = this.midContentTagRepository.findByContentId(contentId);
        if (CollectionUtils.isNotEmpty(set)) {
            Set<Integer> tagIds = Sets.newHashSet();
            for (MidContentTag item : set) {
                tagIds.add(item.getTagId());
            }
            return tagIds;
        }
        return null;
    }

    // 通过f_content.id, 查询f_tag
    public Set<Tag> findByContentId(Integer contentId) {
        Set<Integer> tagIds = this.findTagIdsByContentId(contentId);
        if (CollectionUtils.isNotEmpty(tagIds)) {
            return this.findByIdIn(tagIds);
        }

        return Sets.newHashSet();
    }

    public Set<Tag> findDefault() {
        return this.dao.findByDefaultFlag(true);
    }
}
